package com.itheima.web.servlet.system;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.system.User;
import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import com.itheima.utils.AliyunSmsUtils;
import com.itheima.utils.BeanUtil;
import com.itheima.web.servlet.BaseServlet;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.itheima.utils.AliyunSmsUtils.getNewcode;

/**
 * @Author:Mr.yuan
 * @Description:
 * @Date: Created in 22:19 2020/11/29
 * @ModifiedBy:
 */
@WebServlet("/system/user")
public class UserServlet extends BaseServlet {

    /**
     * @Description: 通过Cookie&Session设置了用户登录&&自动登录
     * @Param: [request, response]
     * @return: void
     * @Author: Mr.yuan
     * @Date: 2020/11/30
     */
    public void loginUser(HttpServletRequest request, HttpServletResponse response) {
        try {

            //1. 获取表单请求参数
            Map<String, String[]> map = request.getParameterMap();
            User user = new User();
            // 封装到user对象中
            BeanUtils.populate(user, map);
            // uu: 查询数据库返回的真实对象.  user: 仅仅封装了用户名和密码而已
            User uu = userService.login(user);

            //3. 判断用户是否存在
            if (uu == null) {
                // 登录失败
                request.setAttribute("msg", "用户名或密码错误");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                return;
            }
            //4. 用户登录成功了
            HttpSession session = request.getSession();
            session.setAttribute("user", uu);

            ////////自动登录(保存用户名和密码)/////
            String autoLogin = request.getParameter("ck");
            if (autoLogin != null) {
                // 用户勾选了"自动登录"
                Cookie cookie = new Cookie("autoLoginCookie", uu.getUsername() + "&" + uu.getPassword());
                //  设置自动登录时间 10天
                cookie.setPath("/");
                cookie.setMaxAge(10 * 24 * 60 * 60);
                response.addCookie(cookie);
            }


            /**
             * @Description: 登录时写入权限字符串
             * @Param:
             * @return:
             * @Author: gjp
             * @Date:
             */
            List<String> permissions = userService.findAllPermissionUrlByUserId(uu.getId());
            session.setAttribute("permissions", permissions);
            /***/


            ////////自动登录(保存用户名和密码)/////
            response.sendRedirect(request.getContextPath() + "/pages/main.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * @Description: 更改用户的账号密码, 成功清除Cookie&&Session重定向
     * @Param: [request, response]
     * @return: void
     * @Author: Mr.yuan
     * @Date: 2020/11/30
     */
    public void updatePWD(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        User user = userService.findById(request.getParameter("id"));
        String password = request.getParameter("password");
        user.setPassword(password);
        userService.updatePWD(user);
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("autoLoginCookie", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        request.getRequestDispatcher("/index.jsp").forward(request, response);


    }

    /**
     * @Description: 请求转发到主页面
     * @Param: [request, response]
     * @return: void
     * @Author: Mr.yuan
     * @Date: 2020/11/30
     */
    public void toLog(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("/pages/main.jsp").forward(request, response);
    }

    /**
     * @Description: 请求转发手機驗證碼查询页面
     * @Param: [request, response]
     * @return: void
     * @Author: Mr.yuan
     * @Date: 2020/11/30
     */
    public void toFindPW(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-findPW.jsp").forward(request, response);
    }


    /**
     * @Description: 獲取驗證碼
     * @Param: [request, response]
     * @return: void
     * @Author: Mr.yuan
     * @Date: 2020/12/1
     */
    public void findPW(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String phoneNum = request.getParameter("phoneNum");
        Pattern CHINA_PATTERN = Pattern.compile("^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$");
        Matcher m = CHINA_PATTERN.matcher(phoneNum);
        if(m.matches()){
            userService.setPhoneCode(phoneNum);
            request.setAttribute("phoneNum", phoneNum);
        }else {
            request.setAttribute("msg","手机号格式不正确");
        }

        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-findPW.jsp").forward(request, response);


    }

    /**
     * @Description:  通過手機號與驗證碼進行登錄
     * @Param: [request, response]
     * @return: void
     * @Author: Mr.yuan
     * @Date: 2020/12/1
     */
    public void loginByPhone(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String codes = request.getParameter("code");
        String phoneNum = request.getParameter("phoneNum");
        String code = userService.findPW(phoneNum);
        User user = userService.findByPhone(phoneNum);
        if (code != null && user!=null&&code.equals(codes)) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            request.getRequestDispatcher("/pages/main.jsp").forward(request, response);
        }else {
            request.setAttribute("msg","用户不存在或验证码错误");
            request.getRequestDispatcher("/WEB-INF/pages/system/user/user-findPW.jsp").forward(request, response);

        }
    }


    /**
     * @Description: 注销登录
     * @Param: [request, response]
     * @return: void
     * @Author: Mr.yuan
     * @Date: 2020/11/30
     */
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.getSession().removeAttribute("user");
        request.getSession().removeAttribute("pcmember");
        Cookie cookie = new Cookie("autoLoginCookie", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        /**
         * @Description: 清楚权限
         * @Param:
         * @return:
         * @Author: gjp
         * @Date:
         */
        request.getSession().removeAttribute("permissions");

        response.sendRedirect(request.getContextPath() + "/index.jsp");

    }

    /**
     * @Description: 请求转发到修改密码页面
     * @Param: [request, response]
     * @return: void
     * @Author: Mr.yuan
     * @Date: 2020/11/30
     */
    public void toUpdatePd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("/WEB-INF/pages/system/user/user-UpdatePW.jsp").forward(request, response);
    }


    /**
     * @Description: 根据用户名称模糊查询所有
     * @Param:[request, response]
     * @return:void
     * @Author:Mr.Cheng
     * @Date:2020/11/30
     */
    public void findAllByUserNameLike(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNum = 1;
        int pageSize = 5;
        String username = "";
        if (StringUtils.isNotBlank(request.getParameter("pageNum"))) {
            pageNum = Integer.parseInt(request.getParameter("pageNum"));
        }
        if (StringUtils.isNotBlank(request.getParameter("pageSize"))) {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }
        if (StringUtils.isNotBlank(request.getParameter("username"))) {
            username = request.getParameter("username");
        }
        PageInfo<User> list = userService.findAllByUserNameLike(username, pageNum, pageSize);
        request.setAttribute("page", list);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/user-list.jsp").forward(request, response);

    }

    /**
     * @Description: 分页 用户名称 联合查询 所有
     * @Param:[request, response]
     * @return:void
     * @Author:Mr.Cheng
     * @Date:2020/11/30
     */
    public void toAdd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/user-add.jsp").forward(request, response);
    }

    /**
     * @Description: 保存新增的用户
     * @Param:[request, response]
     * @return:void
     * @Author:Mr.Cheng
     * @Date:2020/11/30
     */
    public void save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = BeanUtil.fillBean(request, User.class);

        userService.save(user);
        response.sendRedirect(request.getContextPath() + "/system/user?operation=findAllByUserNameLike");
    }


    /**
     * @Description: 批量删除
     * @Param:[request, response]
     * @return:void
     * @Author:Mr.Cheng
     * @Date:2020/11/30
     */
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String deleteArrays = "";
        try {
            deleteArrays = request.getParameter("deleteArrays");
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<String> userIds = new ObjectMapper().readValue(deleteArrays, new TypeReference<List<String>>() {
        });
        for (String userId : userIds) {
            userService.delete(userId);
        }
    }

    /**
     * @Description: 跳转到修改页面
     * @Param:[request, response]
     * @return:void
     * @Author:Mr.Cheng
     * @Date:2020/11/30
     */
    public void toUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userId = "";
        try {
            userId = request.getParameter("id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = userService.findByUserId(userId);
        request.setAttribute("users", user);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/user-add.jsp").forward(request, response);
    }

    /**
     * @Description: 修改
     * @Param:[request, response]
     * @return:void
     * @Author:Mr.Cheng
     * @Date:2020/11/30
     */
    public void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User users = new User();
        try {
            users = BeanUtil.fillBean(request, User.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        userService.update(users);
        response.sendRedirect(request.getContextPath() + "/system/user?operation=findAllByUserNameLike");
    }

    /**
     * @Description: 点击更新角色 回显该用户所有权限
     * @Param:[request, response]
     * @return:void
     * @Author:Mr.Cheng
     * @Date:2020/11/30
     */
    public void author(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = "";
        try {
            userId = request.getParameter("id");
        } catch (Exception e) {
            e.printStackTrace();
        }

        User user = userService.findByUserId(userId);
        List<Map> roleList = userService.findAllRoleByUserId(userId);

        request.setAttribute("users", user);
        request.setAttribute("roleList", roleList);
        request.getRequestDispatcher(request.getContextPath() + "/WEB-INF/pages/system/user/user-role-add.jsp").forward(request, response);
    }

    /**
         * @Description: 对修改后用户绑定的权限 进行保存
         * @Param:[request, response]
         * @return:void
         * @Author:Mr.Cheng
         * @Date:2020/11/30
         */
    public void saveRoleToUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userId = "";
        String[] roleIds = {};

        try {
            userId = request.getParameter("userId");
            roleIds = request.getParameterValues("ids");
        } catch (Exception e) {
            e.printStackTrace();
        }
        userService.saveRoleToUser(roleIds, userId);
        response.sendRedirect(request.getContextPath() + "/system/user?operation=findAllByUserNameLike");
    }
}
